package com.czy.owner.ui.garage;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.HotCarBrandAdapter;
import com.czy.owner.adapter.PickBrandAdapter;
import com.czy.owner.adapter.PickLineAdapter;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.callback.RecyclerHeadersDecoration;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarBrandModel;
import com.czy.owner.entity.CarBrandSubsModel;
import com.czy.owner.global.Constants;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.disk.DiskLruCacheHelper;
import com.czy.owner.utils.pinyin.CharacterParser;
import com.czy.owner.widget.PageTitleView;
import com.czy.owner.widget.RecyclerSideBar;
import com.czy.owner.widget.RoundImageView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;

import static android.app.Activity.RESULT_OK;

/**
 * Created by hedepu on 2018-02-27
 */

public class PickBrandFragment extends BaseFragment {

    public static final int RETURN_FLAG = 99;
    private PageTitleView pageTitle;
    @BindView(R.id.ll_root)
    LinearLayout llRoot;
    @BindView(R.id.ll_garage_search)
    LinearLayout llSearch;
    @BindView(R.id.rv_pick_brand)
    RecyclerView rvPickBrand;
    @BindView(R.id.tv_pick_brand_dialog)
    TextView tvPickBrandDialog;
    @BindView(R.id.rvs_pick_brand_sidebar)
    RecyclerSideBar rvsPickBrandSideBar;
    private CharacterParser characterParser;
    private PickBrandComparator pinyinComparator;
    private PickBrandAdapter mPickBrandAdapter;
    private PickLineAdapter mPickLineAdapter;
    private List<CarBrandModel> mCarBrand = new ArrayList<>();
    private CarBrandModel mSelectedCarBrand, mSelectedCarLine;
    private List<CarBrandSubsModel> mCarLineData = new ArrayList<>();
    private List<CarBrandModel> mCarLine = new ArrayList<>();
    private List<CarBrandModel> mCarForm = new ArrayList<>();
    private boolean isNeedReturnResult = false;

    private LinearLayout llSelectedBrand;
    private PopupWindow popupWindowLine, popupWindowForm;
    private Dialog dialogLine;
    private DiskLruCacheHelper cacheHelper;

    @Override
    protected int attachLayoutRes() {
        return R.layout.frament_pick_brand;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        try {
            cacheHelper = new DiskLruCacheHelper(getActivity());
        } catch (IOException e) {
            e.printStackTrace();
        }
//        pageTitle = new PageTitleView((RelativeLayout) getActivity().findViewById(R.id.rl_page_title), getResources().getString(R.string.garage_pick_brand), true);
//        pageTitle.getLeftButton().setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                getActivity().finish();
//            }
//        });
        if (getActivity().getIntent().getIntExtra(PickBrandActivity.START_FLAG, 0) == 0) {
            isNeedReturnResult = false;//添加
        } else {
            isNeedReturnResult = true;//修改
        }

        MyLog.d("RAVEN","PickBrand  needResult = " + isNeedReturnResult);
        initBrandList();
        llSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchBrandActivity.class);
                intent.putExtra(PickBrandActivity.START_FLAG, isNeedReturnResult);
                startActivityForResult(intent, 1);
            }
        });
    }

    @Override
    protected void updateViews() {

    }



    private RecyclerView rvHotCarBrand;
    private HotCarBrandAdapter hotCarBrandAdapter;
    private void setHeaderView(RecyclerView view){
        View header = LayoutInflater.from(getActivity()).inflate(R.layout.layout_hot_car_brand, view,false);
        rvHotCarBrand = (RecyclerView) header.findViewById(R.id.rv_hot_car_brand);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(),5);
        rvHotCarBrand.setLayoutManager(layoutManager);
        hotCarBrandAdapter = new HotCarBrandAdapter(mContext);
        rvHotCarBrand.setAdapter(hotCarBrandAdapter);
        hotCarBrandAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<CarBrandModel>() {
            @Override
            public void onItemClick(View view, int position, CarBrandModel o) {
                mSelectedCarBrand = o;
                if (o.getSubCounts() > 0) {
//                    llSelectedBrand = (LinearLayout) view.findViewById(R.id.slide_content_layout);
//                    llSelectedBrand.setBackgroundColor(getResources().getColor(R.color.garage_pick_brand_item_background_selected));
                    //showPopupWindowLine();
                    showDialogLine();
                } else {
                    //o.setImageSrc(mSelectedCarBrand.getImageSrc());
                    if (isNeedReturnResult) {
                        Intent intent = new Intent();
                        intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, o);
                        getActivity().setResult(Constants.ACTIVITY_RESULT_CODE_RESET_BRAND, intent);
                        getActivity().finish();
                    } else {
                        Intent intent = new Intent(getActivity(), EditCarActivity.class);
                        intent.putExtra(EditCarActivity.ACTION_TYPE_KEY, EditCarActivity.ACTION_TYPE.ADD);
                        intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, o);
                        startActivityForResult(intent, 0);
                    }
                }
            }
        });

        mPickBrandAdapter.setHeaderView(header);
        getHotBrandData();
    }

    private void initBrandList() {
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PickBrandComparator();

        rvsPickBrandSideBar.setOnTouchingLetterChangedListener(new RecyclerSideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                int position = mPickBrandAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    rvPickBrand.scrollToPosition(position + 1);
                }

            }
        });

        if (mCarBrand != null && mCarBrand.size() > 0) {
            Collections.sort(mCarBrand, pinyinComparator);
        }

        if (mPickBrandAdapter == null) {
            mPickBrandAdapter = new PickBrandAdapter(getActivity(), mCarBrand);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
            rvPickBrand.setLayoutManager(layoutManager);
            rvPickBrand.setAdapter(mPickBrandAdapter);

            final RecyclerHeadersDecoration headersDecor = new RecyclerHeadersDecoration(mPickBrandAdapter);
            rvPickBrand.addItemDecoration(headersDecor);
            rvPickBrand.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
            setHeaderView(rvPickBrand);
            mPickBrandAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
                @Override
                public void onChanged() {
                    headersDecor.invalidateHeaders();
                }
            });

            mPickBrandAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<CarBrandModel>() {
                @Override
                public void onItemClick(int position, CarBrandModel o, View view) {
//                    if(position == 0 ) return;
                    mSelectedCarBrand = o;
                    if (o.getSubCounts() > 0) {
                        llSelectedBrand = (LinearLayout) view.findViewById(R.id.slide_content_layout);
                        llSelectedBrand.setBackgroundColor(getResources().getColor(R.color.garage_pick_brand_item_background_selected));
                        //showPopupWindowLine();
                        showDialogLine();
                    } else {
                        //o.setImageSrc(mSelectedCarBrand.getImageSrc());
                        if (isNeedReturnResult) {
                            Intent intent = new Intent();
                            intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, o);
                            getActivity().setResult(Constants.ACTIVITY_RESULT_CODE_RESET_BRAND, intent);
                            getActivity().finish();
                        } else {
                            Intent intent = new Intent(getActivity(), EditCarActivity.class);
                            intent.putExtra(EditCarActivity.ACTION_TYPE_KEY, EditCarActivity.ACTION_TYPE.ADD);
                            intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, o);
                            startActivityForResult(intent, 0);
                        }
                    }

                }
            });
        } else {
            mPickBrandAdapter.notifyDataSetChanged();
        }
        rvsPickBrandSideBar.setMaxHeight(20);
        rvsPickBrandSideBar.setTextView(tvPickBrandDialog);
    }

    public void getHotBrandData() {
        mLoadView.ShowLoadView(getResources().getString(R.string.refresh_loading));
        hotCarBrandAdapter.clear();
        final RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_CAR_HOT_BRAND);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
        String strData = "";
        if (cacheHelper != null) {
            strData = cacheHelper.getAsString(params.getUri());
        }
        if (strData == null || TextUtils.isEmpty(strData) || "[]".equals(strData)) {
            mLoadView.ShowLoadView(getResources().getString(R.string.refresh_loading));
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    String data = PhoneUtils.checkResponseFlag(getActivity(), result);
                    if (data != null) {
                        if (cacheHelper != null) {
                            cacheHelper.put(params.getUri(), data);
                        }

                        try {
                            Gson gson = new GsonBuilder().create();
                            List<CarBrandModel> hotCarBrand = gson.fromJson(data, new TypeToken<List<CarBrandModel>>() {
                            }.getType());
                            hotCarBrandAdapter.addAll(hotCarBrand);
                        } catch (Exception e) {

                        }
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                    getBrandData();
                }
            });

        } else {
            mLoadView.CancleLoadView();
            try {
                Gson gson = new GsonBuilder().create();
                List<CarBrandModel> hotCarBrand = gson.fromJson(strData, new TypeToken<List<CarBrandModel>>() {
                }.getType());
                hotCarBrandAdapter.addAll(hotCarBrand);
            } catch (Exception e) {

            }
        }


    }

    public void getBrandData() {
        final RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_CAR_BRAND);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
        String strData = "";
        if (cacheHelper != null) {
            strData = cacheHelper.getAsString(params.getUri());
        }
        if (strData == null || TextUtils.isEmpty(strData) || "[]".equals(strData)) {
//            mLoadView.ShowLoadView(getResources().getString(R.string.refresh_loading));
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    String data = PhoneUtils.checkResponseFlag(getActivity(), result);
                    if (data != null) {
                        if (cacheHelper != null) {
                            cacheHelper.put(params.getUri(), data);
                        }

                        try {
                            Gson gson = new GsonBuilder().create();
                            mCarBrand = gson.fromJson(data, new TypeToken<List<CarBrandModel>>() {
                            }.getType());
                        } catch (Exception e) {

                        }
                        Collections.sort(mCarBrand, pinyinComparator);
                        mPickBrandAdapter.setList(mCarBrand);
                        rvsPickBrandSideBar.setSortLetter(mPickBrandAdapter.getArraySortLetters());
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    mLoadView.CancleLoadView();
                }
            });

        } else {
            mLoadView.CancleLoadView();
            try {
                Gson gson = new GsonBuilder().create();
                mCarBrand = gson.fromJson(strData, new TypeToken<List<CarBrandModel>>() {
                }.getType());
            } catch (Exception e) {

            }
            Collections.sort(mCarBrand, pinyinComparator);
            mPickBrandAdapter.setList(mCarBrand);
        }


    }

    private void getLineData() {

        final RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_CAR_BRAND_SUB);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
        params.addBodyParameter("superCarBrandId", "" + mSelectedCarBrand.getCarBrandId());
        //MyLog.i("King", "getLineData:"+Constants.APP_API_BASE + Constants.OWN_CAR_BRAND_SUB+"|" + UserHelper.getInstance().getSessionInfoModel(this).getSession()+"|"+ mSelectedCarBrand.getCarBrandId());
        String strData = "";
        if (cacheHelper != null) {
            strData = cacheHelper.getAsString(params.getUri() + "?" + mSelectedCarBrand.getCarBrandId());
            strData = null;
        }
        mCarLine = new ArrayList<>();
        mCarLineData = new ArrayList<>();
        if (strData == null || TextUtils.isEmpty(strData) || "[]".equals(strData)) {
            mLoadView.ShowLoadView(getResources().getString(R.string.refresh_loading));
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    String data = PhoneUtils.checkResponseFlag(getActivity(), result);
                    if (data != null) {
                        if (cacheHelper != null) {
                            cacheHelper.put(params.getUri() + "?" + mSelectedCarBrand.getCarBrandId(), data, 7 * 24 * 3600 * 1000);
                        }
                        try {
                            Gson gson = new GsonBuilder().create();
                            mCarLineData = gson.fromJson(data, new TypeToken<List<CarBrandSubsModel>>() {
                            }.getType());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        for (int i = 0; i < mCarLineData.size(); i++) {
                            if (mCarLineData.get(i).getSubs().size() > 0) {
                                for (int j = 0; j < mCarLineData.get(i).getSubs().size(); j++) {
                                    CarBrandModel cbm = mCarLineData.get(i).getSubs().get(j);
                                    cbm.setSuperCarBrandName(mCarLineData.get(i).getChName());
                                    mCarLine.add(cbm);
                                }
                            } else {
                                CarBrandModel cbm = new CarBrandModel(mCarLineData.get(i));
                                cbm.setSuperCarBrandName(cbm.getChName());
                                cbm.setSuperCarBrandId(cbm.getCarBrandId());
                                mCarLine.add(cbm);
                            }

                        }

                        Collections.sort(mCarLine, new PickLineComparator());
                        mPickLineAdapter.setList(mCarLine);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    mLoadView.CancleLoadView();
                }
            });
        } else {
            try {
                Gson gson = new GsonBuilder().create();
                mCarLineData = gson.fromJson(strData, new TypeToken<List<CarBrandSubsModel>>() {
                }.getType());
            } catch (Exception e) {
                e.printStackTrace();
            }
            for (int i = 0; i < mCarLineData.size(); i++) {
                if (mCarLineData.get(i).getSubs().size() > 0) {
                    for (int j = 0; j < mCarLineData.get(i).getSubs().size(); j++) {
                        CarBrandModel cbm = mCarLineData.get(i).getSubs().get(j);
                        cbm.setSuperCarBrandName(mCarLineData.get(i).getChName());
                        mCarLine.add(cbm);
                    }
                } else {
                    CarBrandModel cbm = new CarBrandModel(mCarLineData.get(i));
                    cbm.setSuperCarBrandName(cbm.getChName());
                    cbm.setSuperCarBrandId(cbm.getCarBrandId());
                    mCarLine.add(cbm);
                }
            }
            Collections.sort(mCarLine, new PickLineComparator());
            mPickLineAdapter.setList(mCarLine);
        }
    }

    private void showDialogLine() {
        if (mSelectedCarBrand == null) {
            return;
        }

        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_window_garage_line, null);
        ImageView ivCancel = (ImageView) contentView.findViewById(R.id.iv_pop_window_cancel);
        TextView tvTitle = (TextView) contentView.findViewById(R.id.tv_pop_window_title);
        final RoundImageView ivAvatar = (RoundImageView) contentView.findViewById(R.id.iv_pick_brand_item_avatar);
        TextView tvCarName = (TextView) contentView.findViewById(R.id.tv_pick_brand_item_title);
        tvTitle.setText("选择车系");

        x.image().bind(ivAvatar, mSelectedCarBrand.getImageSrc(), new Callback.CommonCallback<Drawable>() {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ivAvatar.setImageResource(R.mipmap.default_icon);
            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onCancelled(CancelledException cex) {
                ivAvatar.setImageResource(R.mipmap.default_icon);
            }

            @Override
            public void onSuccess(Drawable result) {
            }
        });
        tvCarName.setText(mSelectedCarBrand.getChName());

        RecyclerView rvPickLine = (RecyclerView) contentView.findViewById(R.id.rv_pop_window_car_line_member);
        mCarLine = new ArrayList<>();
        mPickLineAdapter = new PickLineAdapter(getActivity(), mCarLine);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        rvPickLine.setLayoutManager(layoutManager);
        rvPickLine.setAdapter(mPickLineAdapter);

        final RecyclerHeadersDecoration headersDecor = new RecyclerHeadersDecoration(mPickLineAdapter);
        rvPickLine.addItemDecoration(headersDecor);
        rvPickLine.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));

        mPickLineAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                headersDecor.invalidateHeaders();
            }
        });

        mPickLineAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<CarBrandModel>() {
            @Override
            public void onItemClick(int position, CarBrandModel o, View view) {

                dealBrand(o);
            }
        });
        dialogLine = new Dialog(getActivity(), R.style.AlertDialogStyle);
        dialogLine.setContentView(contentView);
        dialogLine.setCancelable(true);
        dialogLine.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialogLine.getWindow();
        dialogWindow.setWindowAnimations(R.style.AnimationPopWindow);
        dialogWindow.setGravity(Gravity.RIGHT | Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            /*lp.x = 0;
            lp.y = 0;*/

        Rect outRect = new Rect();
        getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect);

        WindowManager windowManager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        Display mDisplay = windowManager.getDefaultDisplay();
        lp.height = (int) (outRect.height() - PhoneUtils.dip2px(getActivity(), 50));
        dialogWindow.setAttributes(lp);
        dialogLine.show();
        getLineData();
    }

    private void dealBrand(CarBrandModel carBrandModel){
        getPLData(carBrandModel);//获取下一级的数据，排量。没有则跳转编辑页面
    }

    private void getPLData(final CarBrandModel carBrandModel){
        final RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_CAR_BRAND_ALL_ATTR);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(getContext()).getSession());
        params.addBodyParameter("carBrandId", "" + carBrandModel.getCarBrandId());
        MyLog.d("RAVEN","params = " + params);
        mLoadView.ShowLoadView();
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.d("RAVEN","result = " + result);
                String data = PhoneUtils.checkResponseFlag((Activity) mContext, result);
                if (data != null) {
                    try {
                        Gson gson = new GsonBuilder().create();
                        List<CarBrandModel> carPL = gson.fromJson(data, new TypeToken<List<CarBrandModel>>() {
                        }.getType());

                        if(carPL != null && carPL.size() > 0){//有下一级数据
                            Intent intent = new Intent(getActivity(),SelCarOtherAttrActivity.class);
                            intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, carBrandModel);
                            intent.putExtra(SelCarOtherAttrActivity.FIRST_LIST_DATA, (Serializable) carPL);
                            intent.putExtra(SelCarOtherAttrActivity.IS_NEED_RESULT_DATA, isNeedReturnResult);
                            if(isNeedReturnResult) {
                                startActivityForResult(intent,PickBrandActivity.REQUEST_BRAND_CODE);
                            }else {
                                intent.putExtra(EditCarActivity.ACTION_TYPE_KEY, EditCarActivity.ACTION_TYPE.ADD);
                                startActivityForResult(intent, 0);
                            }
                        }else {//没下级数据了
                            if(isNeedReturnResult){
                                Intent intent = new Intent();
                                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, carBrandModel);
                                getActivity().setResult(Constants.ACTIVITY_RESULT_CODE_RESET_BRAND, intent);
                                getActivity().finish();
                            } else {
                                Intent intent = new Intent(getActivity(), EditCarActivity.class);
                                intent.putExtra(EditCarActivity.ACTION_TYPE_KEY, EditCarActivity.ACTION_TYPE.ADD);
                                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, carBrandModel);
                                startActivityForResult(intent, 0);
                            }
                        }

                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    private class PickBrandComparator implements Comparator<CarBrandModel> {

        public int compare(CarBrandModel o1, CarBrandModel o2) {
            if (o1.getFirstLetter().equals("@")
                    || o2.getFirstLetter().equals("#")) {
                return -1;
            } else if (o1.getFirstLetter().equals("#")
                    || o2.getFirstLetter().equals("@")) {
                return 1;
            } else {
                return o1.getFirstLetter().compareTo(o2.getFirstLetter());
            }
        }

    }

    private class PickLineComparator implements Comparator<CarBrandModel> {

        public int compare(CarBrandModel o1, CarBrandModel o2) {
            if (o1.getSuperCarBrandId() < o2.getSuperCarBrandId()) {
                return -1;
            } else if (o1.getSuperCarBrandId() > o2.getSuperCarBrandId()) {
                return 1;
            } else {
                return 0;
            }
        }

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MyLog.d("RAVEN","Fragemne requestCode = " + requestCode);
        MyLog.d("RAVEN","resultCode = " + resultCode);
        if (requestCode == 0 && resultCode == Constants.ACTIVITY_RESULT_CODE_CAR_ADD) {
            getActivity().setResult(Constants.ACTIVITY_RESULT_CODE_CAR_ADD);
            getActivity().finish();
        }

        if (requestCode == PickBrandActivity.REQUEST_BRAND_CODE && resultCode == Constants.ACTIVITY_RESULT_CODE_RESET_BRAND) {
            String pl = data.getStringExtra("selected_car_pl");
            String nf = data.getStringExtra("selected_car_nf");
            CarBrandModel selectedCarModel = (CarBrandModel) data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
            Intent intent = new Intent();
            intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, selectedCarModel);
            intent.putExtra("selected_car_pl", pl);
            intent.putExtra("selected_car_nf", nf);
            getActivity().setResult(Constants.ACTIVITY_RESULT_CODE_RESET_BRAND, intent);
            getActivity(). finish();
        }

        /**处理搜索*/
        if (requestCode == 1 && resultCode == Constants.ACTIVITY_RESULT_CODE_CAR_ADD) {
            getActivity().setResult(Constants.ACTIVITY_RESULT_CODE_CAR_ADD);
            getActivity().finish();
        }

        if (requestCode == 1 && resultCode == Constants.ACTIVITY_RESULT_CODE_RESET_BRAND) {
            String pl = data.getStringExtra("selected_car_pl");
            String nf = data.getStringExtra("selected_car_nf");
            CarBrandModel selectedCarModel = (CarBrandModel) data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
            Intent intent = new Intent();
            intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, selectedCarModel);
            intent.putExtra("selected_car_pl", pl);
            intent.putExtra("selected_car_nf", nf);
            getActivity().setResult(Constants.ACTIVITY_RESULT_CODE_RESET_BRAND, intent);
            getActivity(). finish();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dialogLine != null) {
            dialogLine.dismiss();
        }
    }
}
